package wang.kentwang.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import wang.kentwang.beans.Result;
import wang.kentwang.beans.User;
import wang.kentwang.controller.impl.ControllerImpl;

public class MyServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	 /**
	 * 把对象转为json格式的jar
     * gson         谷歌提供的
     * fastJson     阿里提供的
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        String uname = req.getParameter("uname");
        String sex = req.getParameter("sex");
        String age = req.getParameter("age");
        System.out.println("uname="+uname+"--sex="+sex+"--age="+age);
        //out.print("ajax success");
        User user = new User();
        user.setId(2);
        user.setName(uname);
        user.setPhone(sex);
        user.setAge(Integer.valueOf(age));
        /*//将java中的对象转换为json对象
        String userStr = JSON.toJSONString(user);
        out.print(userStr);*/
        
        //查询数据库用户数据
        ControllerImpl ci=new ControllerImpl();
        ci.add(user);
        List<User> userList = ci.queryAll();
        System.out.println(userList);
        Result result = new Result();
        result.setCode(200);
        result.setMsg("success");
        result.setCount(userList.size());
        result.setList(userList);
        //通过JSON. toJSONString方法，把result对象转为js可解析的json对象
        System.out.println(result);
        out.print(JSON.toJSONString(result));
        out.close();

        //由json对象解析为user对象
		/*
		 * String userStr = "{\n" + "            \"uname\":\"小张\",\n" +
		 * "            \"sex\":\"男\",\n" + "            \"age\":12\n" + "        }";
		 * User userJson = JSON.parseObject(userStr,User.class);
		 * System.out.println("userJson-->"+userJson);
		 */
	}
	
}
